// proxy.js
const fs = require('fs')
const path = require('path')

const encoding = 'utf-8'
/**
 * 获取配置文件内容 getContent('proxy-config.json')
 * @param filename env.json
 * @returns {string}
 */
const getContent = filename => {
  const dir = path.resolve(process.cwd(), 'environments')
  return fs.readFileSync(path.resolve(dir, filename), { encoding })
}

const jsonParse = obj => {
  // eslint-disable-next-line no-new-func
  return Function('"use strict";return (' + obj + ')')()
}

/**
 * 获取配置选项 getConfig()
 * @returns {{}|*}
 */
const getConfig = () => {
  try {
    return jsonParse(getContent('proxy-config.json'))
  } catch (e) {
    return {}
  }
}

module.exports = {
  proxy: {
    '/gimishare': {
      target: 'http://localhost:5555/gimishare', // 因为有router存在所以这个target可有可无，但是得有一个占位符不能为空
      changeOrigin: true,
      secure: false,
      router: () => (getConfig() || {}).target || '',
      pathRewrite: {
        '^/gimishare': ''
      }
    },
    '/upload': {
      target: 'http://localhost:3031/upload',
      changeOrigin: true,
      secure: false,
      router: () => (getConfig() || {})['upload-target'] || '',
      pathRewrite: {
        '^/upload': ''
      }
    }
  }
}
